package cn.stacey.spring.ssm.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.stacey.spring.ssm.domain.AjaxResponse;
import cn.stacey.spring.ssm.domain.Post;
import cn.stacey.spring.ssm.mapper.PostMapper;

@Service
public class PostService {
	@Autowired
	PostMapper mapper;
	public List<Post> findAll() {
//		SqlSession session=null;	
//		SqlSessionFactory factory = SessionFactoryUtils.getFactory();
//			session = factory.openSession();
	//	mapper = session.getMapper(PostMapper.class);
		//用了代理对象可以删掉上面几句话，因为CategoryServlet中调用了本方法，
		//而在PostService中引用了ServiceProxyUtils类中的代理对象
			
				List<Post> all = mapper.findAll();
//				session.close();
				return all;
		
	}
	/**
	 * 
	 * @param page 从前台传来的第几页 
	 * @param size
	 * @return
	 */
	public AjaxResponse<Post> findPage(int page,int size){
		
//		SqlSession session=null;
//		SqlSessionFactory factory = SessionFactoryUtils.getFactory();
//		session = factory.openSession();
//		mapper = session.getMapper(PostMapper.class);
		//用了代理对象可以删掉上面几句话，因为CategoryServlet中调用了本方法，
				//而在PostService中引用了ServiceProxyUtils类中的代理对象
		AjaxResponse<Post> result=new AjaxResponse<>();
		//当前页数据
		List<Post> findPage = mapper.findPage((page-1)*size, size);
		result.setData(findPage);
		//一共有多少条数据
		int count = mapper.findCount();
		result.setCount(count);
//		session.close();
		return result;
	}
	
	public void deleteBatch(String[] ids) {
		mapper.deleteBatch(ids);
		
	}
	
	public AjaxResponse<Post> searchPage(String title,Integer cid,Date created,int page,int size) {
//		String title = p.getTitle();
//		Date created = p.getCreated();
//		Integer cid = null;
		//复制的
		if(title!=null&&title.length()!=0) {
			title="%"+title+"%";
		}
		AjaxResponse<Post> result=new AjaxResponse<>();
		List<Post> searchPost = mapper.searchPost(title, cid, created, (page-1)*size, size);
		result.setData(searchPost);
		//总共的查出来的数据
		int searchCount = mapper.findCount();
		result.setCount(searchCount);
		return result;
	}
	public void insert(Post p) {
		mapper.addPost(p);
	}
	public Post getById(int id) {
		return mapper.getById(id);
	}
	public void deleteById(int id) {
		mapper.deleteById(id);
		
	}
	public void update(int id, Post p) {
		mapper.update(id,p);
		
	}
	public Post getByIdWithCategory(int id) {
		return mapper.findByIdWithCategory(id);
	}

	public void update1(int id, Post post) {
		mapper.update1(id, post);
		
	}
	public List<Post> search(Post post) {
		//在数据库查询语句中写了模糊查询like 在此处也要写
		if(post.getTitle()!=null&&post.getTitle().length()!=0) {
			post.setTitle("%"+post.getTitle()+"%");
		}
		return mapper.search(post);
	}

		
}
